package cn.krui.project.service.system;

import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.krui.helper.db.DBHelper;
import cn.krui.helper.db.SQL;
import cn.krui.helper.db.SQL.InsertSQL;
import cn.krui.helper.db.SQL.SelectSQL;
import cn.krui.helper.db.SQL.UpdateSQL;
import cn.krui.helper.tools.SecurityUtils;
import cn.krui.helper.tools.WebToolsUtils;
import cn.krui.project.bean.system.sys_user.sys_user;
import cn.krui.project.bean.system.sys_user.sys_user_login;
import cn.krui.project.bean.system.sys_user.sys_user_pwd;
import nl.bitwalker.useragentutils.Browser;
import nl.bitwalker.useragentutils.OperatingSystem;
import nl.bitwalker.useragentutils.UserAgent;

/**
 * @program: project-system
 * @description: 后台登录模块
 * @author: zc
 * @create: 2019-10-16
 **/
@Service
public class LoginService {
	@Autowired
	private DBHelper dbHelper;
	private final String EQUALS_PASSWD = "passwd";
	/**
	 * 后台登录
	 */
	public sys_user sysLogin(sys_user_login user) throws NoSuchAlgorithmException {
		Map<String, Object> whereMap = new HashMap<>(1);
		whereMap.put("user_name", user.getUser_name());
		sys_user sysUser = dbHelper.selectOne(
				"qsu.id,qsu.user_name,qsu.passwd,qsu.status,qsu.error_count,qsu.token,qsu.old_token,qsu.role_id,qsu.group_id",
				"qr_sys_users qsu", "user_name=#{user_name}", whereMap, sys_user.class);
		UserAgent userAgent = UserAgent.parseUserAgentString(WebToolsUtils.getUserAgent());
		// 获取浏览器信息
		Browser browser = userAgent.getBrowser();
		// 获取系统信息
		OperatingSystem os = userAgent.getOperatingSystem();

		// 写登录日志
		InsertSQL logSql = SQL.insert("qr_sys_login_logs").addValuePart("user_type", 1, 0)
				.addValuePart("user_id", sysUser == null ? 0 : sysUser.getId(), 0)
				.addValuePart("user_name", user.getUser_name(), 0)
				.addValuePart("log_ip", WebToolsUtils.getClientIP(), 0).addValuePart("os", os.getName(), 0)
				.addValuePart("browser", browser.getName(), 0).addValuePart("create_time", new Date(), 0);

		if (sysUser != null
				&& sysUser.getPasswd().toLowerCase().equals(SecurityUtils.md5(user.getPasswd()).toLowerCase())) {
//			if(sysUser.getError_count()>=3) { 
//				Object img_code_ck = redisService.get(user.getImg_uuid());
//				if(img_code_ck==null) { 
//					log_sql.addValuePart("log_memo", "未输入验证码",0);
//					dbHelper.insert(log_sql);
//					return sysUser; 
//				}
//				//验证图形验证码
//				if(!img_code_ck.equals(user.getImg_code())) { 
//					log_sql.addValuePart("log_memo", "验证码错误",0);
//					dbHelper.insert(log_sql);
//					return sysUser;
//				}
//			}
			sysUser.setError_count(0);
			logSql.addValuePart("log_memo", "登录成功", 0);
			dbHelper.insert(logSql);
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			sysUser.setOld_token(sysUser.getToken());
			sysUser.setToken(uuid);
			UpdateSQL updateSql = SQL.update("qr_sys_users").addField("error_count", 0)
					.addField("token", sysUser.getToken()).addField("old_token", sysUser.getOld_token())
					.where("id=" + sysUser.getId());
			dbHelper.update(updateSql);
			// 获取菜单和权限
			whereMap.clear();
			whereMap.put("role_id", sysUser.getRole_id());
			whereMap.put("group_id", sysUser.getGroup_id());
			Map<String, Object> roleMenuPermission = dbHelper.selectOne("qsr.role_menu,qsr.role_permissions",
					"qr_sys_role qsr", "qsr.id=#{role_id} and qsr.group_id=#{group_id}", whereMap);
			if (roleMenuPermission.size() > 0) {
				sysUser.setRole_menu(roleMenuPermission.get("role_menu") + "");
				sysUser.setRole_permissions(roleMenuPermission.get("role_permissions") + "");
			}
			return sysUser;
		}
		if (sysUser != null) {
			UpdateSQL updateSql = SQL.update("qr_sys_users").addField("error_count", sysUser.getError_count() + 1)
					.where("id=" + sysUser.getId());
			dbHelper.update(updateSql);
		}
		if (sysUser == null) {
			logSql.addValuePart("log_memo", "账号不存在", 0);
			dbHelper.insert(logSql);
		} else {
			logSql.addValuePart("log_memo", "密码错误", 0);
			dbHelper.insert(logSql);
			sysUser.setError_count(sysUser.getError_count() + 1);
			return sysUser;
		}
		return null;
	}

	/**
	 * 修改密码
	 * 
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public Integer repwd(sys_user_pwd pwdm) throws NoSuchAlgorithmException {
		String where = String.format("id=%s", pwdm.getUid());
		SelectSQL sql = SQL.select("passwd").from("qr_sys_users").where(where);
		Map<String, Object> sMap = dbHelper.selectOne(sql);
		if (sMap.size() <= 0){
			return null;
		}
		String newpwd = SecurityUtils.md5(pwdm.getOldpwd());
		if (!sMap.get(EQUALS_PASSWD).equals(newpwd)){
			// 原密码错误
			return -1; 
		}
		newpwd = SecurityUtils.md5(pwdm.getNewpwd());
		UpdateSQL uSql = SQL.update("qr_sys_users").addField("passwd", newpwd).where(where);
		if (dbHelper.update(uSql) > 0){
			// 成功
			return 1; 
		}
		return null;
	} 

	/**
	 * 权限字符串按模块划分 eg: /{module}/xx  需要后续模块统一路径命名
	 * @param pers
	 * @return
	 */
	public Map<String,String> rolePermissionsToMap(String pers){
		if (StringUtils.isEmpty(pers)) {
			return new HashMap<>(0);
		}
		Map<String,List<String>> map = new HashMap<>(100);
		String[] strRolePermissions = pers.split(",");
		for (String str : strRolePermissions) {
			int first = str.indexOf("/", 0); 
			int second = str.indexOf("/", first+1);
			if(first==-1 || second==-1){
				if(!map.containsKey("")){
					List<String> eplist = new ArrayList<String>();
					eplist.add(str);
					map.put("", eplist);
				}else{
					map.get("").add(str);
				}
				continue;
			}
			String module = str.substring(first+1, second);
			if(!map.containsKey(module)){
				List<String> flist = new ArrayList<String>();
				flist.add(str);
				map.put(module, flist);
			}else{
				map.get(module).add(str);
			}
		}
		Map<String,String> out = new HashMap<>(100);
		for (String str : map.keySet()) {
			out.put(str, String.join(",", map.get(str)));
		}
		return out;
	}
}
